<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>商品管理</span>
        <div class="extra">
          <el-button type="primary" @click="visibleDrawer = true;title = '添加商品';handle = '上架'">添加商品</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
            <el-form-item label="商品分类：">
                <el-select placeholder="请选择" v-model="choosed_category" style="width:200px">
                    <el-option 
                        v-for="c in categorys" 
                        :key="c.id" 
                        :label="c.categoryName"
                        :value="c.categoryName">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="getGoods">搜索</el-button>
                <el-button @click="choosed_category=''">重置</el-button>
            </el-form-item>
        </el-form>
    <!-- 商品列表 -->
    <el-table :data="goods" style="width: 100%">
      <el-table-column label="商品图像">
        <template #default="{ row }">
          <img :src=row.image style="width: 100px; object-fit: cover;">
        </template>
      </el-table-column>
      <el-table-column
        label="商品名称"
        width="400"
        prop="title"
      ></el-table-column>
      <el-table-column label="分类" prop="category"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="updateGoodsForm(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteGoods(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
    <el-drawer
      v-model="visibleDrawer"
      :title=title
      direction="rtl"
      size="50%"
    >
      <!-- 添加商品表单 -->
      <el-form :model="goodsModel" label-width="120px" :rules="rules">
        <el-form-item label="商品名称" prop="title">
          <el-input
            v-model="goodsModel.title"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input
            v-model="goodsModel.price"
            placeholder="请输入商品价格"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品出产省份" prop="province">
          <el-input
            v-model="goodsModel.province"
            placeholder="请输入商品出产省份"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品出产市区" prop="area">
          <el-input
            v-model="goodsModel.area"
            placeholder="请输入商品出产市区"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select placeholder="请选择" v-model="goodsModel.category">
            <el-option
              v-for="c in categorys"
              :key="c.id"
              :label="c.categoryName"
              :value="c.categoryName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品封面">
          <el-upload
            v-model:file-list="goodsImagesList"
            list-type="picture-card"
            action="http://8.138.173.30:8080/GoodsImages/uploadImage"
            :headers="{ 'Customer': tokenStore.token}"
            :on-preview="handleImagePictureCardPreview"
            :on-remove="handleImageRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="goodsImagesDialogVisible">
            <img w-full 
              :src="goodsImagesDialogImageUrl" 
              :headers="{ 'Customer': tokenStore.token}"
              alt="Preview Image" 
            />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品内容">
          <el-upload
            v-model:file-list="goodsDetailsList"
            list-type="picture-card"
            action="http://8.138.173.30:8080/GoodsDetail/uploadDetailsImage"
            name="file"
            :headers="{ 'Customer': tokenStore.token}"
            :on-preview="handleDetailPictureCardPreview"
            :on-remove="handleDetailRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="goodsDetailsDialogVisible">
            <img w-full 
              :src="goodsDetailsDialogImageUrl" 
              :headers="{ 'Customer': tokenStore.token}"
              alt="Preview Image" 
            />
          </el-dialog>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFunction">{{ handle }}</el-button>
          <el-button type="info" @click="cancleAddGoods">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>

<script lang="ts" setup>
import { Edit, Delete } from "@element-plus/icons-vue";

import { ref } from "vue";
import { getGoodsByBusinessService, getGoodsByPageService, updateGoodsService, addGoodsService, deleteGoodsService, deleteGoodsDetailsImageService, addGoodsDetailsImageService, updateGoodsDetailsImageService, getGoodsDetailsImageService, deleteGoodsImageService, getGoodsImageService, addGoodsImageService, updateGoodsImageService, deleteGoodsAllDetailsImagesService, deleteGoodsAllImagesService } from "@/api/goods";
import { ElMessage, ElMessageBox, UploadProps, UploadUserFile } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { useBusinessInfoStore } from "@/store/businessInfo";
import { useTokenStore } from '@/store/token';

//商品分类数据模型
const categorys = ref([
  {'id': 1, 'categoryName': '食品'},
  {'id': 2, 'categoryName': '电子产品'},
  {'id': 3, 'categoryName': '生活用品'},
]);

//商家信息
const businessInfoStore = useBusinessInfoStore();

const tokenStore = useTokenStore();

//控制是添加商品还是编辑商品
const title = ref('');

//控制添加/编辑商品下的按钮
const handle = ref('');

//保存在编辑商品时的旧商品名
const old_title = ref('');

//用户搜索时选中的分类
const choosed_category = ref("");

//商品列表数据模型
const goods = ref([]);

//分页条数据模型
const pageNum = ref(1); //当前页
const total = ref(20); //总条数
const pageSize = ref(3); //每页条数

//商品详细信息
const goodsDetailsList = ref([]);
const goodsDetailsListToAdd = ref([]);
const goodsDetailsDialogImageUrl = ref('');
const goodsDetailsDialogVisible = ref(false);

//商品封面信息
const goodsImagesList = ref([]);
const goodsImagessListToAdd = ref([]);
const goodsImagesDialogImageUrl = ref('');
const goodsImagesDialogVisible = ref(false);

const handleImageRemove: UploadProps['onRemove'] = async (uploadFile, uploadFiles) => {
  //当指定要删除某张商品封面图后删除该商品封面图
  if(uploadFile.response && uploadFile.response.data)
  await deleteGoodsImageService(uploadFile.response.data);
  else await deleteGoodsImageService(uploadFile.url);
}

const handleImagePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  //查看商品封面大图
  goodsImagesDialogImageUrl.value = uploadFile.url!
  goodsImagesDialogVisible.value = true;
}

const handleDetailRemove: UploadProps['onRemove'] = async (uploadFile, uploadFiles) => {
  //当指定要删除某张商品详细图删除该商品详细图
  if(uploadFile.response && uploadFile.response.data)
  await deleteGoodsDetailsImageService(uploadFile.response.data);
  else await deleteGoodsDetailsImageService(uploadFile.url);
}

const handleDetailPictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  //查看商品详细大图
  goodsDetailsDialogImageUrl.value = uploadFile.url!
  goodsDetailsDialogVisible.value = true;
}

//当每页条数发生了变化，调用此函数
const onSizeChange = (size: any) => {
  pageSize.value = size;
  getGoods();
};
//当前页码发生变化，调用此函数
const onCurrentChange = (num: any) => {
  pageNum.value = num;
  getGoods();
};

//获取该商家上架的全部商品
const getGoods = async () => {
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    category: choosed_category.value ? choosed_category.value : null,
  };
  const result = await getGoodsByPageService(params);
  total.value = result.data.total;
  goods.value = result.data.items;
};

getGoods();

//控制抽屉(添加商品)是否显示
const visibleDrawer = ref(false);
//添加表单数据模型
const goodsModel = ref({
  title: "",
  category: "",
  price: "",
  province: "",
  area: "",
  salesnum: "0",
  business: businessInfoStore.businessInfo.name,
  image: ""
});

//用于规定输入框的规则
const rules = {
  title: [
    { required: true, message: "请输入商品名", trigger: "blur" },
  ],
  price: [
    { required: true, message: "请输入价格", trigger: "blur" },
    {
      pattern: /^\d{1,8}(\.\d{1,2})?$/,
      message: "价格必须是10位数字(且最多只能有2位小数)",
      trigger: "blur",
    },
  ],
  province: [
    { required: true, message: "请输入商品出产省", trigger: "blur" },
  ],
  area: [
    { required: true, message: "请输入商品出产市区", trigger: "blur" },
  ],
  image: [
    { required: true, message: "请导入商品封面图", trigger: "change" },
  ],
};

const clearGoodsModel = () => {
  goodsModel.value = {
    title: "",
    category: "",
    price: "",
    province: "",
    area: "",
    salesnum: "0",
    business: businessInfoStore.businessInfo.name,
    image: ""
  };
}

//取消编辑/添加商品
const cancleAddGoods = async () => {
  clearGoodsModel();
  if(title.value == '添加商品')
  {
    for(let i = 0; i < goodsDetailsList.value.length; i++) {
      await deleteGoodsDetailsImageService(goodsDetailsList.value.at(i).response.data);
    }
    for(let i = 0; i < goodsImagesList.value.length; i++) {
      await deleteGoodsImageService(goodsImagesList.value.at(i).response.data);
    }
  }
  goodsDetailsList.value = [];
  goodsImagesList.value = [];
  visibleDrawer.value = false;
  if(title.value == '添加商品') {
    ElMessage({
        type: 'info',
        message: '商家取消了上架操作',
    });
  }else {
    ElMessage({
        type: 'info',
        message: '商家取消了编辑操作',
    });
  }
}

//点击编辑商品后执行的操作
const updateGoodsForm = async( row: any) => {
  title.value = '编辑商品';
  handle.value = '提交修改';
  visibleDrawer.value = true;
  const goods_name = row.title;
  //先获取到商品信息
  const params = new Map([
    ['goods_name', goods_name,]
  ])
  const result = await getGoodsByBusinessService(params);
  goodsModel.value = result.data;
  const result2 = await getGoodsDetailsImageService(result.data.id);
  const result3 = await getGoodsImageService(result.data.id);
  goodsDetailsList.value = result2.data.map(item => ({ url: item.goodsDetail}));
  goodsImagesList.value = result3.data.map(item => ({ url: item.goodsImage}));
  old_title.value = goodsModel.value.title;
}

//添加/编辑商品操作
const handleFunction = async () => {
  //判断是添加商品操作还是编辑商品操作
  if(title.value == '添加商品') {
    //添加商品
    console.log(goodsModel.value.category);
    goodsModel.value.image = goodsImagesList.value.at(0).response.data;
    const result = await addGoodsService(goodsModel.value);

    for(let i = 0; i < goodsImagesList.value.length; i++) {
      goodsImagessListToAdd.value.push(goodsImagesList.value.at(i).response.data);
    }
    await addGoodsImageService(goodsImagessListToAdd.value, result.data);
    goodsImagessListToAdd.value=[];
    goodsImagesList.value = [];

    for(let i = 0; i < goodsDetailsList.value.length; i++) {
      goodsDetailsListToAdd.value.push(goodsDetailsList.value.at(i).response.data);
    }
    await addGoodsDetailsImageService(goodsDetailsListToAdd.value, result.data);
    goodsDetailsListToAdd.value=[];
    goodsDetailsList.value = [];
    
    ElMessage.success(result.message ? result.message : "添加成功");
  }
  else {
    //编辑商品
    if(goodsImagesList.value.at(0).response && goodsImagesList.value.at(0).response.data)
    goodsModel.value.image = goodsImagesList.value.at(0).response.data;
    else goodsModel.value.image = goodsImagesList.value.at(0).url;
    const result = await updateGoodsService(old_title.value, goodsModel.value);
    for(let i = 0; i < goodsImagesList.value.length; i++) {
      if(goodsImagesList.value.at(i).response && goodsImagesList.value.at(i).response.data) {
        goodsImagessListToAdd.value.push(goodsImagesList.value.at(i).response.data);
      }else {
        goodsImagessListToAdd.value.push(goodsImagesList.value.at(i).url);
      }
    }
    await updateGoodsImageService(goodsImagessListToAdd.value, goodsModel.value.id);
    goodsImagessListToAdd.value=[];
    for(let i = 0; i < goodsDetailsList.value.length; i++) {
      if(goodsDetailsList.value.at(i).response && goodsDetailsList.value.at(i).response.data) {
        goodsDetailsListToAdd.value.push(goodsDetailsList.value.at(i).response.data);
      }else {
        goodsDetailsListToAdd.value.push(goodsDetailsList.value.at(i).url);
      }
    }
    await updateGoodsDetailsImageService(goodsDetailsListToAdd.value, goodsModel.value.id);
    goodsDetailsListToAdd.value=[];
    ElMessage.success(result.message ? result.message : "修改成功");
  }
  clearGoodsModel();
  visibleDrawer.value = false;
  getGoods();
}

//删除操作
//头像下的条目点击后调用的函数
const deleteGoods = async(row: any) => {
  //删除商品
  ElMessageBox.confirm(
    '您确认要删除该商品吗?',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    //确认了删除商品
    const data = new Map([
      ['title', row.title],
    ])
    const result = await deleteGoodsService(data);
    await deleteGoodsAllDetailsImagesService(row.id);
    await deleteGoodsAllImagesService(row.id);
    ElMessage({
      type: result.message!=='操作成功' ? 'error' : 'success',
      message: result.messagee!=='操作成功' ? result.message : '删除商品成功',
    });
    getGoods();
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '商家取消了删除商品',
    })
  })
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>